import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Slf4j
public class JedisPoolUtil {

    private static volatile JedisPool jedisPool = null;//被volatile修饰的变量不会被本地线程缓存，对该变量的读写都是直接操作共享内存。

    //单例模式，构造方法私有化，不能new，要对外提供一个静态方法返回一个实例
    private JedisPoolUtil() {
    }

    public static JedisPool getJedisPoolInstance() {
        if (null == jedisPool) {
            synchronized (JedisPoolUtil.class) {
                if (null == jedisPool) {
                    JedisPoolConfig poolConfig = new JedisPoolConfig();
                    //poolConfig.setMaxActive(1000);
                    poolConfig.setMaxIdle(32);
                    //poolConfig.setMaxWait(100 * 1000);
                    /*高版本中用以下两个属性替换
                    maxActive  ==>  maxTotal
                    maxWait    ==>  maxWaitMillis
                    */
                    poolConfig.setMaxTotal(1000);
                    poolConfig.setMaxWaitMillis(100 * 1000);
                    poolConfig.setTestOnBorrow(true);

                    //jedisPool = new JedisPool(poolConfig, "127.0.0.1");
                    jedisPool = new JedisPool(poolConfig, "192.168.1.6", 6379);
                }
            }
        }
        return jedisPool;
    }

    public static void release(JedisPool jedisPool, Jedis jedis) {
        if (null != jedis) {
            //returnBrokenResource|returnResource废弃
            //jedisPool.returnResourceObject(jedis);
            //jedisPool.returnResource(jedis);

            try {
                jedis.close();
                log.info("已释放jedis资源");
            } catch (Exception e) {
                log.error("释放jedis资源出错，将要关闭jedis，异常信息：" + e.getMessage());
                if (jedis != null) {
                    try {
                        // 2. 客户端主动关闭连接
                        jedis.disconnect();
                    } catch (Exception e1) {
                        log.error("disconnect jedis connection fail: " , e);
                    }finally {
                    }
                }
            }
        }
    }
}